<?php
/**
 * Created by PhpStorm.
 * User: wchuang
 * Date: 2016/8/27
 * Time: 15:15
 */
namespace common\services;

use common\models\BuyJob;
use common\models\BuyjobUser;
use common\models\LydbUserQuery;
use yii;
class BuyService extends NetService
{
	/**
	 * userNum*userBuyNum = buyNum
	 */

	public function __construct()
	{

	}

	/**
	 *
	 * @param int $pageNum
	 * @return null
	 */
	public function getRemoteHotGoods($pageNum = 1)
	{
		$pageNum = (int) $pageNum;
		$requestUrl = self::SERVER_URL . "/xingluo/rest/app_lydb/goods/SearchByHot";
		if($pageNum){
			$response = $this->reset()
				->setOption(
					CURLOPT_POSTFIELDS,
					http_build_query(array(
							'pageNum'     => $pageNum
						)
					))
				->post($requestUrl);
			return json_decode($response,true);
		}else{
			return null;
		}
	}

	public function getHotGoods($pageNum = 1){
		$remoteRes = $this->getRemoteHotGoods($pageNum);
		if($remoteRes && $remoteRes['code'] == 0){
			if(isset($remoteRes['info'])){
				return $remoteRes['info'];
			}else{
				return null;
			}
		}else{
			return null;
		}
	}
	/**
	 * 获取夺宝商品详情
	 * @param $goodId
	 * @return null
	 */
	public function getRemoteGoodInfo($goodId){
		$requestUrl = self::SERVER_URL . "/xingluo/rest/app_lydb/goods/GoodsDetails";
		if($goodId){
			$response = $this->reset()
				->setOption(
					CURLOPT_POSTFIELDS,
					http_build_query(array(
							'singleGoodsId'     => $goodId
						)
					))
				->post($requestUrl);
			return json_decode($response,true);
		}else{
			return null;
		}
	}

	/**
	 * 获取商品详情
	 * @param $goodId
	 * @return null
	 */
	public function getGoodInfo($goodId){
		$remoteRes = $this->getRemoteGoodInfo($goodId);
		if($remoteRes && $remoteRes['code'] == 0){
			if(isset($remoteRes['info'])){
				return $remoteRes['info'];
			}else{
				return null;
			}
		}else{
			return null;
		}
	}

	/**
	 * 将商品加入购物车
	 * @param $user
	 * @param $goodId
	 * @param $buyNum
	 * @return null
	 */
	public function addRemoteGoodToCart($user,$goodId,$buyNum){
		$requestUrl = self::SERVER_URL . "/xingluo/rest/app_lydb/goods/AddShoppingCart";
		$token = (new UserService())->getToken($user);

		if($goodId && $token){
			$response = $this->reset()
				->setOption(
					CURLOPT_POSTFIELDS,
					http_build_query(array(
							'id'        => $goodId,
							'number'    =>  $buyNum
						)
					))
				->setOption(CURLOPT_HTTPHEADER,array(
						"token:" . $token
					)
				)
				->post($requestUrl);

			return json_decode($response,true);
		}else{
			return null;
		}
	}
	
	/**
	 * 获取远程购物车
	 * @param $user
	 * @return null
	 */
	public function getRemoteCart($user){
		$requestUrl = self::SERVER_URL . "/xingluo/rest/app_lydb/goods/GetShoppingCart";
		$token = (new UserService())->getToken($user);

		if($token){
			$response = $this->reset()
				->setOption(CURLOPT_HTTPHEADER,array(
						"token:" . $token
					)
				)
				->post($requestUrl);

			return json_decode($response,true);
		}else{
			return null;
		}
	}
	
	/**
	 * 获取购物车
	 * @param object $user
	 * @return array
	 */
	public function getCart($user){
		$remoteCartRes = $this->getRemoteCart($user);
		if($remoteCartRes && $remoteCartRes['code'] == 0){
			return $remoteCartRes['attributes'];
		}else{
			return [];
		}
	}
	public function cleanRemoteCart($user,$id){
		$requestUrl = self::SERVER_URL . "/xingluo/rest/app_lydb/goods/DeleteShoppingCart";
		$token = (new UserService())->getToken($user);

		if($user && $token && $id){
			$response = $this->reset()
				->setOption(
					CURLOPT_POSTFIELDS,
					http_build_query(array(
							'id'        => $id
						)
					))
				->setOption(CURLOPT_HTTPHEADER,array(
						"token:" . $token
					)
				)
				->post($requestUrl);
			return json_decode($response,true);
		}else{
			return null;
		}
	}
	public function cleanCart($user){
		$cart = $this->getCart($user);

		if($cart){
			foreach($cart as $one){
				$res[] = $this->cleanRemoteCart($user,$one['id']);
			}

			$newCart = $this->getCart($user);
			if($newCart){
				return false;
			}else{
				return true;
			}
		}else{
			return true;
		}
	}
	/**
	 * 远程提交订单
	 * @param object $user
	 * @return array
	 */
	public function settleRemoteCart($user){
		$requestUrl = self::SERVER_URL . "/xingluo/rest/app_lydb/shoppingcart/buy";

		$token = (new UserService())->getToken($user);
		$cart = $this->getCart($user);

		if($cart && is_array($cart) && $token){
			$amountMoney = 0;
			foreach ($cart as $v){
				$amountMoney = isset($v['number']) ? $amountMoney + $v['number'] : $amountMoney;
			}

			$response = $this->reset()
				->setOption(
					CURLOPT_POSTFIELDS,
					http_build_query(array(
							'rmbNum'    =>  $amountMoney
						)
					))
				->setOption(CURLOPT_HTTPHEADER,array(
						"token:" . $token
					)
				)
				->post($requestUrl);

			return json_decode($response,true);
		}else{
			return [];
		}
	}

	/**
	 * 结算购物车
	 * @param $user
	 * @return bool
	 */
	public function settleCart($user){
		$addCartRes = $this->settleRemoteCart($user);
		if(isset($addCartRes) && $addCartRes['code'] == 0){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 加入购物车
	 * @param $user
	 * @param $goodId
	 * @param $buyNum
	 * @return bool
	 */
	public function addGoodsToCart($user,$goodId,$buyNum){
		$addCartRes = $this->addRemoteGoodToCart($user,$goodId,$buyNum);
		if($addCartRes && is_array($addCartRes)){
			if($addCartRes['code'] == 0 && $addCartRes['info'] > 0){
				return true;
			}else{
				return false;
			}
		}else{
			return true;
		}

	}

	/**
	 * 创建自动下单任务
	 *
	 * @param $goodId
	 * @param $buyNum
	 * @param int $buyUser
	 * @return BuyJob
	 */
	public function createBuyJob($goodId,$buyNum,$buyUser = 10){
		/**
		 * 规则
		 *      每个用户抢币数为：1 ~ ($buyNum / $buyUser)*2
		 *      每次一个用户下单抢，直到抢完预订数量为止（当最后一次数量不对时，忽略当次操作)
		 */

		/**
		 * 产生单用户购买范围 ： 1 - $maxBuy
		 */
		$maxBuy = (int) $buyNum / $buyUser;
		if($maxBuy <= 0){
			return null;
		}
		//查询商品
		$goodsInfo = $this->getGoodInfo($goodId);
		if(!($goodsInfo && is_array($goodsInfo))){
			return null;
		}
		//商品不可购买
		if($goodsInfo['status'] != 0){
			return null;
		}
		$curCanBuyNum = $goodsInfo['AllJoinNum'] - $goodsInfo['CurrentJoinNum'];

		//可购买数不足
		if($curCanBuyNum < $buyNum){
			return null;
		}

		/**
		 * 创建任务记录
		 */
		$buyJob = new BuyJob();
		$buyJob->good_id    = $goodId;
		$buyJob->issue      = $goodsInfo['CurrentNum'];
		$buyJob->buy_num    = $buyNum;
		$buyJob->user_num   = $buyUser;
		$buyJob->create_time = time();

		if(!$buyJob->save()){
			//创建任务失败
			return null;
		}

		$hasBuyNum = 0;
		$userRealNum = 0;
		$LydbUserQuery = new LydbUserQuery();
		$UserService = new UserService();
		while ($hasBuyNum < $buyNum){
			$user = $LydbUserQuery->getRandOne();
			$token = $UserService->getToken($user);
			if(!$token){
				//当前用户不可用
				continue;
			}
			$curBuyNum = mt_rand(1,$maxBuy);
			$addToCart = $this->addGoodsToCart($user,$goodId,$curBuyNum);
			if(!$addToCart){
				//加入购物车失败
				continue;
			}
			$cartGoods = $this->getCart($user);
			if(!$cartGoods || !is_array($cartGoods)){
				//购物车为空
				continue;
			}

			$settleCartRes  = $this->settleCart($user);
			if($settleCartRes){
				$hasBuyNum += $curBuyNum;
			}else{
				//结算失败
				$this->cleanCart($user);
				continue;
			}

			// 创建用户-任务记录
			$buyJobUser = new BuyjobUser();
			$buyJobUser->user_id = $user->id;
			$buyJobUser->buyjob_id = $buyJob->id;
			$buyJobUser->buy_num    = $curBuyNum;
			$buyJobUser->create_time = time();
			$buyJobUser->save();
			$userRealNum++;
		}
		// 更新任务信息
		$buyJob->user_num_real  = $userRealNum;
		$buyJob->buy_num_real   =   $hasBuyNum;
		$buyJob->save();

		return $buyJob;
	}
}